package com.mdlib.helper.api.network;

import android.support.v4.app.FragmentActivity;

import com.ljlib.core.app.AppManager;
import com.ljlib.core.util.common.NetworkUtils;
import com.mdlib.helper.app.AppContext;
import com.mdlib.helper.model.BaseResult;
import com.mdlib.helper.ui.UIHelper;
import com.mdlib.helper.utils.ToastUtil;
import com.orhanobut.logger.Logger;

import java.io.IOException;

import retrofit2.adapter.rxjava.HttpException;
import rx.Subscriber;

/**
 * Created by librabin on 16/11/7.
 */

public abstract class RxSubscribe<T> extends Subscriber<T> {

    @Override
    public void onError(Throwable e) {
        String errorMsg = "";

        if (e instanceof IOException) {
            if (NetworkUtils.isAvailable(AppContext.getInstance())) {
                errorMsg = "网络不可用";
            } else {
                errorMsg = e.getMessage();
            }
        } else if (e instanceof HttpException) {
            HttpException httpException = (HttpException) e;
            errorMsg = httpException.response().message();
        } else if (e instanceof ApiException) {
            ApiException exception = (ApiException) e;
            int code = exception.getErrorCode();
            onFail(code, e.getMessage(), exception.getErrorData());
        } else {
            errorMsg = e.getMessage();
        }

        onFail(errorMsg);
    }

    @Override
    public void onNext(T response) {
        try {
            if (response instanceof BaseResult) {
                BaseResult baseResult = (BaseResult) response;
                if (baseResult.code  != 0) {
                    onFail(baseResult.msg);
                } else {
                    onSucc(response);
                }
            } else {
                onSucc(response);
            }

        } catch (Exception e) {
//            onFail("01");
        }

    }

    @Override
    public void onCompleted() {

    }


    protected abstract void onSucc(T t);

    protected abstract void onFail(String msg);

    protected void onFail(int code, String msg, String data) {
        switch (code) {
            case ApiErrorCode.ERROR_PARSER:
                break;
            case ApiErrorCode.LOGIN_OUT:
                outLogin();
                break;
            case ApiErrorCode.SESSION_ID_OUT:
                outLogin();
                break;
            case ApiErrorCode.ERROR_SESSION_INVALID:
                Logger.e("sessionid过期");
                ToastUtil.showToast("sessionid过期");
                break;
            default:
        }

        onFail(msg);
    }


    private void outLogin() {
        final FragmentActivity activity = (FragmentActivity) AppManager.getAppManager().currentActivity();
        UIHelper.showLoginOut(activity);

    }

}
